package com.huangfuyi.process.actuator.monitor;

import com.huangfuyi.process.actuator.enums.EPMonitorThreadStatus;
import com.huangfuyi.process.actuator.threadpool.EPSlowThreadPool;
import com.huangfuyi.process.entity.monitor.EPMonitorInfo;
import com.huangfuyi.process.entity.monitor.EPMonitorSlowTaskCheckInfo;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;

/**
 * 定时清理核心线程池中执行时间超长的任务
 *
 * 清理方式：将运行任务的线程从核心线程池中转移到慢任务线程池
 * */
public class EPMonitorSlowTaskCheckThread extends EPMonitorThread<List<EPMonitorSlowTaskCheckInfo>>{

    private static final Logger log = Logger.getLogger("SlowTaskCheckThread");

    public EPMonitorSlowTaskCheckThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        // 当前线程被标记为销毁时，不继续运行
        while (!isDestruction()){
            EPMonitorInfo<List<EPMonitorSlowTaskCheckInfo>> monitorInfo = this.getMonitorInfo();

            // 任务执行前，更新运行信息
            monitorInfo.setStatus(EPMonitorThreadStatus.RUNNING);
            monitorInfo.setStartTime(System.currentTimeMillis());

            // 进行慢任务检测
            ArrayList<EPMonitorSlowTaskCheckInfo> checkResults = new ArrayList<>();
            try {
                EPSlowThreadPool.slowCheck(checkResults);
                monitorInfo.setSuccess(true);
                monitorInfo.setMessage("慢任务检测： 检测成功");
                log.info("慢任务检测： 检测成功");
            }catch (Throwable t){
                StringWriter stackInfo = new StringWriter();
                t.printStackTrace(new PrintWriter(stackInfo));
                monitorInfo.setSuccess(false);
                monitorInfo.setMessage(stackInfo.toString());
                log.warning(String.format(Locale.ROOT, "慢任务检测： 运行失败！原因：%s", monitorInfo.getMessage()));
            }

            monitorInfo.setData(checkResults);

            // 检测执行完成后，更新线程运行信息
            monitorInfo.setStatus(EPMonitorThreadStatus.FINISH);
            monitorInfo.setEndTime(System.currentTimeMillis());

            try {
                sleep(monitorInfo.getRunInterval());
            } catch (InterruptedException e) {
                log.warning(String.format(Locale.ROOT, "慢任务检测： 等待唤醒失败！原因：%s", e.getMessage()));
                setDestruction(true);
            }
        }
    }
}
